<template>
	<view class="content">
		<view class="top-area">
			<view class="top-tilte">{{topTile}}</view>
			<view class="top-btns">
				<view class="btn-item" @click="goDanger">
					<image class="img" src="../../../static/images/icon/min2.png" /> {{$t('inspection.area.hazard')}}
				</view>
				<view class="btn-item" @click="showBeforeInspect">
					<image class="img" src="../../../static/images/icon/min1.png" /> {{$t('inspection.taskPlan.inspPreparation')}}
				</view>
				<view class="btn-item" @click="goSummanryPage">
					<image class="img" src="../../../static/images/icon/min4.png" /> {{$t('inspection.taskPlan.finishReport')}}
				</view>
				<view class="btn-item" @click="giveUpTastFun">
					<image class="img" src="../../../static/images/icon/min3.png" /> {{$t('inspection.taskExecute.giveUpInspection')}}
				</view>
			</view>
		</view>

		<scroll-view scroll-y :class="notEdit ? 'commonList' : 'scrollList'">
			<template v-for="(item, index) in ListData">
				<view class="list-item" :key="index" @click="toInfo(item)">
					<view class="item-row">
						<view class="row-data" v-if="isAreaLocation == 1">
							<text class='title'>{{$t('inspection.area.areaNo')}}：</text>
							<text class="desc">{{item.areaNo}}</text>
						</view>
						<view class="row-data" v-if="isAreaLocation == 0">
							<text class='title'>{{$t('equipment.common.devCode')}}：</text>
							<text class="desc">{{item.locaNo}}</text>
						</view>
						<view class="row-data">
							<text class="red" v-if="item.areaExecStatus == 0">{{$t('inspection.taskExecute.unchecked')}}</text>
							<text class="orange" v-if="item.areaExecStatus == 1">{{$t('inspection.taskExecute.partialInspection')}}</text>
							<text class="green" v-if="item.areaExecStatus == 2">{{$t('inspection.taskExecute.allInspection')}}</text>
							<image class="img" src="../../../static/images/icon/min5.png"></image>
						</view>
					</view>
					<view class="item-row" v-if="isAreaLocation == 1">
						<view class="row-data">
							<text class='title'>{{$t('inspection.area.areaName')}}：</text>
							<text class="desc">{{item.areaName}} </text>
						</view>
					</view>
					<view class="item-row" v-if="isAreaLocation == 0">
						<view class="row-data">
							<text class='title'>{{$t('equipment.common.devName')}}：</text>
							<text class="desc">{{item.locaName}} </text>
						</view>
					</view>
				</view>
			</template>
		</scroll-view>
		
		<view class="bottomBtn" v-if="showBtn">
			<button type="primary" @click="handleBtn">{{ btnText }}</button>
		</view>
	</view>
</template>

<script>
	import * as inspApi from '@/api/business/inspect.js'
	import { notice, utilities } from '@/utils/common.js'
	import { getDefectLevelList } from '@/api/business/defect.js'
	import { findByTypeKeyExtend } from '@/api/platform/common.js'
	import * as sqliteUtil from '@/utils/sqlite.js'
	import * as sqliteInspect from '@/utils/business/inspectSqlite.js'
	import * as sqliteDefect from '@/utils/business/defectSqlite.js'
	import { inspect as util } from '@/utils/business/common.js'
	import NFCMixin from '@/utils/business/businessNFC.js'

	export default {
		mixins: [
			NFCMixin
		],
		data() {
			return {
				ListData: [],
				taskId: '',
				topTile: '',
				lineId: '',
				isAreaLocation: 1,
				isScanHand: '',
				preparing: '', //巡检前准备
				notEdit: false,
				showBtn: false,
				btnText: '',
				btnType: '',
				networkStatus: 'online',
				nfcData: ''
			}
		},
		computed: {
			openOffline() {
				return utilities.getConfig('PROJECT').OPEN_OFFLINE
			},
		},
		watch: {
			nfcData: {
				handler(val) {
					this.handleNfc()
				}
				// immediate: true
			}
		},
		onLoad(option) {
			this.taskId = option.taskId
			this.notEdit = option.notEdit == 2 ? true : false
			this.showBtn = !this.notEdit
			
			// #ifdef APP-PLUS
			this.listenNFCStatus()
			this.readyRead = true
			// #endif
			
			// 业务操作日志
			this.$saveOpLog('detail', 'insp_task', this.taskId)
		},
		onShow() {
			this.ListData = [];
			// 执行页面保存需要时间，此处加延时
			setTimeout(() => {
				this.loadData();
			}, 300)
		},
		onUnload() {
			this.readyRead = false
			uni.removeStorageSync("nfcData")
		},
		methods: {
			async loadData() {
				// 如果不支持离线模式，隐藏离线下载按钮
				if(!this.openOffline) {
					let pages = getCurrentPages();
					let page = pages[pages.length - 1];
					// #ifdef APP-PLUS
					let currentWebview = page.$getAppWebview();
					currentWebview.setTitleNViewButtonStyle(0, {
						width: '0'
					});
					// #endif
				}
				
				await inspApi.getTaskInfo(this.taskId).then(res=>{
					this.topTile = res.data.taskName
					this.lineId = res.data.lineId
					this.preparing = res.data.preparing
					this.isAreaLocation = res.data.isAreaLocation
					this.isScanHand = res.data.isScanHand
					
					if(!this.notEdit) {
						// 扫码
						if(this.isScanHand === 0) {
							this.showBtn = true
							this.btnText = this.$t('inspection.taskExecute.scanOrNfc')
							this.btnType = "QR"
						} 
						// 手工选择
						else if(this.isScanHand === 1) {
							this.showBtn = true
							this.btnText = this.$t('inspection.taskExecute.scanOrNfc')
							this.btnType = "QR"
						}
						// 物联设备
						else if(this.isScanHand === 2) {
							this.showBtn = true
							this.btnText = this.$t('inspection.taskExecute.nfcRead')
							this.btnType = "NFC"
						}
					}
				})
				
				// this.getPreparingFun()
				
				let param = {
					taskId: this.taskId, 
					type: this.isAreaLocation
				}
				uni.showLoading({
					title: this.$t('common.loading')
				})
				inspApi.taskTypeList(param).then((res) => {
					uni.hideLoading()
					if (res.data) {
						this.ListData = res.data;
					} 
				})
			},
			getPreparingFun() {
				if (!this.notEdit && this.preparing) {
					this.showBeforeInspect();
				}
			},
			showBeforeInspect() {
				uni.showModal({
					title: this.$t('inspection.taskPlan.inspPreparation'),
					content: this.preparing,
					showCancel: false,
					confirmText: this.$t('inspection.taskExecute.understood'),
					confirmColor: '#007aff',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			giveUpTastFun() {
				if (this.notEdit) {
					notice.toast(this.$t('inspection.message.inoperable'))
					return
				}
				
				let that = this
				uni.showModal({
					title: this.$t('baseCommon.message.tips'),
					content: this.$t('inspection.message.isGiveUpTask'),
					success: function (res) {
						if (res.confirm) {
							inspApi.giveUpInspTask({ "taskId": that.taskId }).then((res) => {
								if (!res) {
									return
								}
								if (res.code == 0) {
									notice.toast(that.$t('common.field.operationSuccess'))
									setTimeout(() => {
										uni.redirectTo({
											url: "/pages/business/inspect/inspectList"
										})
									}, 1000)
									
									// 删除离线任务数据
									that.deleteOfflineTask()
								} else {
									notice.toast(that.$t('common.field.operationError'))
								}
							})
						}
					}
				})
			},
			async deleteOfflineTask() {
				// 打开sqlite数据库连接
				if(!sqliteUtil.isOpen()) {
					await sqliteUtil.openSqlite()
				}
				
				// 删除 m_ri_task表数据
				sqliteUtil.deleteTableInfo('m_ri_task', 'task_id', this.taskId)
				
				// 查询检查项关联的缺陷
				let defectList = []
				let inspectList = await sqliteUtil.selectTableInfo('m_ri_task_inspection', 'task_id', task.taskId)
				inspectList.forEach(item=>{
					if(item.df_no) {
						defectList.push(item.df_no)
					}
				})
				
				// 删除 m_ri_task_inspection表数据
				sqliteUtil.deleteTableInfo('m_ri_task_inspection', 'task_id', this.taskId)
				
				// 删除 m_df_information表数据
				defectList.forEach(item=>{
					sqliteUtil.deleteTableInfo('m_df_information', 'df_id', item)
				})
				
				// 删除 m_ri_task_down表数据
				sqliteUtil.deleteTableInfo('m_ri_task_down', 'task_id', this.taskId)
			},
			goSummanryPage() {
				uni.navigateTo({
					url: "/pages/business/inspect/inspectSummary?taskId=" + this.taskId + '&topTile=' + this.topTile + '&notEdit=' + this.notEdit
				})
			},
			goDanger() {
				uni.navigateTo({
					url: "/pages/business/inspect/dangerPage?lineId=" + this.lineId
				})
			},
			toInfo(item) {
				let url = "/pages/business/inspect/inspectItem?taskId=" + this.taskId + "&lineId=" + this.lineId + 
					"&areaId=" + item.areaId + "&locaId=" + item.locaId + "&isAreaLocation=" + this.isAreaLocation
				
				if(this.notEdit || this.isScanHand === 0 || this.isScanHand === 2) {
					url += '&isEdit=ok'
				}
				
				uni.navigateTo({
					url: url
				})
				
				let data = ""
				if(this.isAreaLocation === 1) {
					data = "TYPE=IDPOS&ID=" + item.areaId +"&NO=" + item.areaNo
				} else if(this.isAreaLocation === 0){
					data = "TYPE=IDPOS&ID=" + item.locaId +"&NO=" + item.locaNo
				}
				uni.setStorageSync("nfcData", data)
			},
			handleBtn() {
				if(this.btnType == "QR") {
					uni.navigateTo({
						url: "/pages/business/inspect/scanCode?taskId=" + this.taskId + "&lineId=" + this.lineId + "&isAreaLocation=" + this.isAreaLocation
						// url: "/pages/business/inspect/sureCode?taskId=" + this.taskId + "&lineId=" + this.lineId + "&isAreaLocation=" + this.isAreaLocation
					})
				} else if(this.btnType == "NFC") {
					this.nfcData = null
					// NFC读取数据
					this.readData()
				}
			},
			async handleNfc() {
				if(this.nfcData) {
					let that = this
					// 获取当前页面
					let pages = getCurrentPages();
					let page = pages[pages.length - 1];
					
					// 由于NFC功能是mixins，防止watch在其他页面执行，此处限制页面路由
					if(page.route.indexOf('/inspectDetail') !== -1 || page.route.indexOf('/inspectItem') !== -1) {
						let isCurrent = true
						if(page.route.indexOf('/inspectDetail') === -1) {
							isCurrent = false
						}
						
						// 验证
						let result = await util.verifyControlMode(that.taskId, that.nfcData, 'scan', that.networkStatus)
						if(result.isPass) {
							let url = './inspectItem?taskId=' + that.taskId + '&lineId=' + that.lineId + 
								'&areaId=' + result.areaId + '&locaId=' + result.locaId + '&isAreaLocation=' + that.isAreaLocation
							
							if(!isCurrent) {
								let prevNfc = uni.getStorageSync("nfcData")
								// 过滤掉NAME字段
								let nowNfc = that.nfcData.substring(1, that.nfcData.indexOf('&NAME'))
								if(prevNfc && nowNfc != prevNfc) {
									let content = ''
									if(that.isAreaLocation === 1) {
										content = '区域不一致，请确认是否切换'
									} else if(that.isAreaLocation === 0) {
										content = '设备不一致，请确认是否切换'
									}
									uni.showModal({
										title: that.$t('baseCommon.message.tips'),
										content: content,
										success: function (res) {
											if (res.confirm) {
												uni.redirectTo({
													url: url 
												});
												uni.setStorageSync("nfcData", that.nfcData)
											} else if (res.cancel) {
												that.nfcData = ''
											}
										}
									})
								} else {
									uni.redirectTo({
										url: url 
									});
									uni.setStorageSync("nfcData", that.nfcData)
								}
							} else {
								uni.navigateTo({
									url: url
								});
								uni.setStorageSync("nfcData", that.nfcData)
							}
						} else {
							uni.showModal({
								title: that.$t('baseCommon.message.tips'),
								content: result.msg,
								success: function (res) {
									if (res.confirm) {
										if(!isCurrent) {
											page.$vm.pageBack()
											uni.removeStorageSync("nfcData")
										} else {
											that.nfcData = ''
										}
									} else if (res.cancel) {
										that.nfcData = ''
									}
								}
							})
						}
					}
				}
			},
			// 离线下载--同步数据字典
			async syncCode() {
				// sqliteUtil.dropTable('m_ri_code')
				// sqliteUtil.dropTable('m_cpis_cat_dic')
				// sqliteUtil.dropTable('m_df_level')
				
				await sqliteInspect.createMRiCode()
				await sqliteDefect.createMDfLevel()
				await sqliteUtil.createMCpisCatDic()
				
				let taskState = await inspApi.queryByCatNo({ catNo: 'DJ_TASK_STATE' })
				await sqliteUtil.deleteTableInfo('m_ri_code', 'cat_no', 'DJ_TASK_STATE')
				sqliteInspect.insertMRiCodeBatch(taskState.data.codeList)
				// taskState.data.codeList.forEach(code=>{
				// 	sqliteInspect.insertMRiCode(code)
				// })
				
				let codeData = await findByTypeKeyExtend("jldw,zybm,qxlx,sbjscslx")
				
				let measureUnit = codeData.data && codeData.data.jldw ? codeData.data.jldw : []
				await sqliteUtil.deleteTableInfo('m_cpis_cat_dic', 'type_key', 'jldw')
				measureUnit.forEach(code=>{
					code.typeKey = 'jldw'
					// sqliteUtil.insertMCpisCatDic(code)
				})
				sqliteUtil.insertMCpisCatDicBatch(measureUnit)
				
				let majorList = codeData.data && codeData.data.zybm ? codeData.data.zybm : []
				await sqliteUtil.deleteTableInfo('m_cpis_cat_dic', 'type_key', 'zybm')
				majorList.forEach(code=>{
					code.typeKey = 'zybm'
					// sqliteUtil.insertMCpisCatDic(code)
				})
				sqliteUtil.insertMCpisCatDicBatch(majorList)
				
				let dfTypeList = codeData.data && codeData.data.qxlx ? codeData.data.qxlx : []
				await sqliteUtil.deleteTableInfo('m_cpis_cat_dic', 'type_key', 'qxlx')
				dfTypeList.forEach(code=>{
					code.typeKey = 'qxlx'
					// sqliteUtil.insertMCpisCatDic(code)
				})
				sqliteUtil.insertMCpisCatDicBatch(dfTypeList)
				
				let mpTypeList = codeData.data && codeData.data.sbjscslx ? codeData.data.sbjscslx : []
				await sqliteUtil.deleteTableInfo('m_cpis_cat_dic', 'type_key', 'sbjscslx')
				mpTypeList.forEach(code=>{
					code.typeKey = 'sbjscslx'
					// sqliteUtil.insertMCpisCatDic(code)
				})
				sqliteUtil.insertMCpisCatDicBatch(mpTypeList)
				
				let defectLevel = await getDefectLevelList({ pageNo: 1, pageSize: 10 })
				await sqliteUtil.deleteTableInfo('m_df_level')
				sqliteDefect.insertMDfLevelBatch(defectLevel.data.records)
				// defectLevel.data.records.forEach(code=>{
				// 	sqliteDefect.insertMDfLevel(code)
				// })
			},
			// 离线下载
			downloadTask() {
				uni.showLoading({
					title: this.$t('inspection.message.dataDownloading')
				})
				
				// 离线下载
				inspApi.downloadTask({ 'taskId': this.taskId }).then(async res => {
					// 危险点
					let hazard = res.data.riLineHazard
					
					// 路线测点
					let lineMp = res.data.riLineInspMp
					
					// 缺陷
					let defect = res.data.dfMap
					
					// 测量数据
					let mpData = res.data.eqMpData
					
					// 巡检任务
					let task = res.data.riTask[0]
					
					// 检查项
					let inspection = task.taskInspectionList
					
					// 检查项测点
					let inspMp = task.taskInspMpVoList
					
					// 异常情况
					let abnormal = task.taskInspectionAbnormalVoList
					
					// 同步数据字典
					this.syncCode()
					
					// 保存测点数据(已存在的数据不保存)
					let existsData = await sqliteUtil.selectTableInfo('m_eq_mp_data')
					let existsDataIds = []
					existsData.forEach(item=>{
						existsDataIds.push(item.mp_data_id)
					})
					let mpDataList = mpData.filter(r => !existsDataIds.includes(r.mpDataId))
					sqliteInspect.insertMEqMpDataBatch(mpDataList)
					// mpData.forEach(item => {
					// 	// 已存在的数据不保存
					// 	if(!existsDataIds.includes(item.mpDataId)) {
					// 		sqliteInspect.insertMEqMpData(item)
					// 	}
					// })
					
					// 保存危险点
					await sqliteUtil.deleteTableInfo('m_ri_line_hazard', 'line_id', task.lineId)
					hazard.forEach(item => {
						sqliteInspect.insertMRiLineHazard(item)
					})
					
					// 保存路线测点
					await sqliteUtil.deleteTableInfo('m_ri_line_insp_mp', 'line_id', task.lineId)
					sqliteInspect.insertMRiLineInspMpBatch(lineMp)
					// lineMp.forEach(item => {
					// 	sqliteInspect.insertMRiLineInspMp(item)
					// })
					
					// 保存巡检任务
					await sqliteUtil.deleteTableInfo('m_ri_task', 'task_id', task.taskId)
					sqliteInspect.insertMRiTask(task)
					
					// 保存检查项
					await sqliteUtil.deleteTableInfo('m_ri_task_inspection', 'task_id', task.taskId)
					sqliteInspect.insertMRiTaskInspectionBatch(inspection)
					// inspection.forEach(item => {
					// 	sqliteInspect.insertMRiTaskInspection(item)
					// })
					
					// 保存检查项测点
					await sqliteUtil.deleteTableInfo('m_ri_task_insp_mp', 'task_id', task.taskId)
					sqliteInspect.insertMRiTaskInspMpBatch(inspMp)
					// taskMp.forEach(item => {
					// 	sqliteInspect.insertMRiTaskInspMp(item)
					// })
					
					// 保存异常情况
					await sqliteUtil.deleteTableInfo('m_ri_task_inspection_abnormal', 'task_id', task.taskId)
					sqliteInspect.insertMRiTaskInspectionAbnormalBatch(abnormal)
					// abnormal.forEach(item => {
					// 	sqliteInspect.insertMRiTaskInspectionAbnormal(item)
					// })
					
					// 保存缺陷
					defect.forEach(async item => {
						await sqliteUtil.deleteTableInfo('m_df_information', 'df_id', item.dfId)
						// sqliteDefect.insertMDfInformation(item)
					})
					sqliteDefect.insertMDfInformationBatch(defect)
					
					// 新增离线下载记录
					let record = {
						taskId: task.taskId,
						downState: '10',
						downTime: utilities.getNowDateTime(),
						createTime: utilities.getNowDateTime(),
						updateTime: utilities.getNowDateTime()
					}
					sqliteInspect.insertMRiTaskDown(task)
					
					uni.hideLoading()
					
					uni.showModal({
						title: this.$t('baseCommon.message.tips'),
						content: this.$t('inspection.message.downloadCompleted'),
						confirmText: this.$t('inspection.message.enterOfflineMode'),
						success: function (res) {
							if (res.confirm) {
								// 清除token
								uni.removeStorageSync('_app_token');
								// 清除传感器
								uni.removeStorageSync('bindSensor');
								
								uni.navigateTo({
									url: '/pages/business/inspect/offline/index'
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				})
			}
		},
		async onNavigationBarButtonTap() {
			if (this.notEdit) {
				notice.toast(this.$t('inspection.message.inoperable'))
				return
			}
			
			// 打开sqlite数据库连接
			if(!sqliteUtil.isOpen()) {
				await sqliteUtil.openSqlite()
			}
			
			// sqliteUtil.dropTable('m_ri_line_hazard')
			// sqliteUtil.dropTable('m_ri_task')
			// sqliteUtil.dropTable('m_ri_task_inspection')
			// sqliteUtil.dropTable('m_ri_line_insp_mp')
			// sqliteUtil.dropTable('m_ri_task_insp_mp')
			// sqliteUtil.dropTable('m_ri_task_inspection_abnormal')
			// sqliteUtil.dropTable('m_df_information')
			// sqliteUtil.dropTable('m_ri_task_down')
			// sqliteUtil.dropTable('m_eq_mp_data')
			
			// 建表
			await sqliteInspect.createMEqMpData()
			await sqliteInspect.createMRiLineHazard()
			await sqliteInspect.createMRiTask()
			await sqliteInspect.createMRiTaskInspection()
			await sqliteInspect.createMRiLineInspMp()
			await sqliteInspect.createMRiTaskInspMp()
			await sqliteInspect.createMRiTaskInspectionAbnormal()
			await sqliteDefect.createMDfInformation()
			await sqliteInspect.createMRiTaskDown()
			
			// 查询是否已经下载过该任务
			let downTask = await sqliteUtil.selectTableInfo('m_ri_task', 'task_id', this.taskId)
			if(downTask.length > 0) {
				let that = this
				uni.showModal({
					title: this.$t('baseCommon.message.tips'),
					content: this.$t('inspection.message.dataCoverage'),
					success: function (res) {
						if (res.confirm) {
							that.downloadTask()
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			} else {
				this.downloadTask()
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F1F1F1;
	}
	
	.top-area {
		background: white;
	
		.top-tilte {
			padding: 12px 0;
			margin: 0 10px;
			color: #333;
			text-align: left;
			border-bottom: 1rpx solid #eee;
		}
	
		.top-btns {
			height: 45px;
			margin: 0 10px;
			border-bottom: 1rpx solid #eee;
			display: flex;
			align-items: center;
	
			.btn-item {
				font-size: 12px;
				color: #666;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 25%;
				border-right: 1rpx solid #eee;
	
				.img {
					margin-right: 5px;
					width: 16px;
					height: 16px;
				}
			}
	
			.btn-item:last-child {
				border-right: none;
			}
		}
	}
	
	.scrollList {
		background-color: #fff;
		/* #ifdef APP-PLUS */
		height: calc(100vh - 175px);
		/* #endif*/
		/* #ifdef H5 */
		height: calc(100vh - 215px);
		/* #endif*/
	}
	
	.commonList {
		background-color: #fff;
	}

	.list-item {
		width: 100%;
		padding: 15px 10px;
		padding-bottom: 0;
		font-size: 14px;
		color: #333;
		border-bottom: 1rpx solid #eee;
		box-sizing: border-box;
	
		.item-row {
			display: flex;
			align-items: center;
			justify-content: space-between;
	
			.row-data {
				display: flex;
				align-items: center;
				margin-bottom: 15px;
				
				.img {
					width: 12px;
					height: 12px;
					margin-left: 4px;
				}
				
				.title {
					color: #999;
				}
	
				.desc {
					color: #333;
					margin-left: 10px;
				}
			}
		}
	}

	.green {
		color: $uni-color-success;
	}

	.red {
		color: $uni-color-error;
	}
	
	.orange {
		color: $uni-color-warning;
	}
	
	.bottomBtn {
		position: fixed;
		bottom: 5px;
		width: 96%;
		left: 2%;
	
		button {
			background-color: #1E91E6;
		}
	}
</style>
